package record

import (
	"time"

	bkemetrics "gopkg.openfuyao.cn/cluster-api-provider-bke/pkg/metrics"
	"gopkg.openfuyao.cn/cluster-api-provider-bke/utils"
	"gopkg.openfuyao.cn/cluster-api-provider-bke/utils/config"
	"gopkg.openfuyao.cn/cluster-api-provider-bke/utils/log"

	"sigs.k8s.io/controller-runtime/pkg/client"
)

// PhaseDurationRecord record the phase run duration
func PhaseDurationRecord(obj client.Object, phaseName string, startTime time.Time, err error) {
	if config.MetricsAddr == "0" {
		return
	}
	log.Debugf("(%s)record phase %s duration, start time: %v, end time: %v", utils.ClientObjNS(obj), phaseName, bkemetrics.FormatTime(startTime), bkemetrics.TimeNow())

	describe := ""
	if err != nil {
		describe = err.Error()
	}

	key := utils.ClientObjNS(obj)

	bkemetrics.MetricRegister.RecordGaugeVec(
		bkemetrics.PhaseDurationSeconds,
		key,
		phaseName,
		bkemetrics.FormatTime(startTime),
		bkemetrics.TimeNow(),
		describe,
	).Set(time.Since(startTime).Seconds())

	if config.E2EMode {
		if err := bkemetrics.MetricRegister.E2EDataGather(key); err != nil {
			log.Errorf("e2e mode enabled, but failed to save metrics data: %v", err)
			return
		}
	}

}
